package com.hyq.learn.api.config.datasource;

import com.hyq.learn.mybatis.config.CommonEnumTypeHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author heyuqin
 * @date 2024/5/29 17:11
 */
@Configuration
public class MybatisConfiguration {

    // @Bean
    // 这是针对mybatis的拦截器，当自定义多数据源的时候就会失效。
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.addInterceptor(new DatasourceIntercept());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
        org.apache.ibatis.session.Configuration ibatisConfiguration = new org.apache.ibatis.session.Configuration();
        // 设置枚举转换处理器
        ibatisConfiguration.setDefaultEnumTypeHandler(CommonEnumTypeHandler.class);
        ibatisConfiguration.setMapUnderscoreToCamelCase(true);

        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));
        bean.setConfiguration(ibatisConfiguration);

        return bean.getObject();
    }
}
